<template>
  <!-- template中书写组建的结构 -->
  <!-- 大盒子存放背景区域 -->
  <div class="login-container">
    <!-- 小盒子中间登陆区域 -->
    <div class="login-box">
      <!-- 表头盒子 -->
      <div class="title-box"></div>
      <!-- 注册的表单区域 -->
      <el-form ref="form" :model="loginForm" :rules="regRules">
        <el-form-item prop="username">
          <el-input placeholder="请输入用户名" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="btn-reg" @click="loginFn">登录</el-button>
          <el-link type="info" @click="$router.push('/register')">去注册&gt;</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from '@/api'
export default {
  name: 'LoginBox',
  data () {
    return {
      // 表单数据
      loginForm: {
        username: '',
        password: ''
      },
      regRules: { // 表单数据校验规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9]{1,10}$/,
            message: '用户名必须是1-10的大小写字母数字',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15的非空字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    loginFn () {
      this.$refs.form.validate(async valid => {
        // 校验失败
        if (!valid) return false
        // 校验成功，调用接口登录
        const { data: res } = await loginApi(this.loginForm)
        // 登录失败
        if (res.code !== 0) return this.$message.error(res.message)
        // 登录成功
        this.$store.commit('setToken', res.token)
        this.$message.success(res.message)
        this.$router.push('/')
      })
    }
  }
}
</script>

<style lang="less" scoped>
/* style书写组建的样式 */
.login-container {
  height: 100%;
  width: 100%;
  background-size: cover;
  background-image: url("@/assets/images/login_bg.jpg");

  .login-box {
    box-sizing: border-box;
    width: 400px;
    height: 270px;
    background-color: #fff;
    border-radius: 3px;
    padding: 0 30px;
    // 绝对定位
    position: absolute;
    top: 50%;
    left: 50%;
    // 偏移
    transform: translate(-50%, -50%);

    .title-box {
      height: 60px;
      background: url("@/assets/images/login_title.png") center no-repeat;
    }

    .btn-reg {
      width: 100%;
    }
  }
}
</style>
